package com.ttl.bc.ap.stkrequest;

import hibernate.util.HibernateUtil;

import java.util.Iterator;
import java.util.List;

import org.apache.struts.action.ActionForm;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import com.ttl.bc.ap.invoice.action.BCAPInvoice2Form;
import com.ttl.bc.ap.stkrequest.BCStkRequestBean;
import com.ttl.bc.ap.stkrequest.BCStkRequestSubBean;
import com.ttl.bc.ap.stkrequest.BCStkRequestSubShowBean;
import com.ttl.common.db.ADAO;

public class BCStkRequestDAO extends ADAO {
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean update(String s, Object o) {
		
		BCStkRequestBean r = (BCStkRequestBean)o; 
		
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();

            String hql = "FROM BCStkRequestBean h where h.docNo = '"+s+"'";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++){
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);
            	
            	r.setCreatorCode(h.getCreatorCode());
            	r.setCreateDateTime(h.getCreateDateTime());
            	
            	Iterator it = r.getBcStkRequestSubs().iterator();
            	while (it.hasNext()) {
					BCStkRequestSubBean rsub = (BCStkRequestSubBean) it.next();
					rsub.setCreatorCode(r.getCreatorCode());
					rsub.setCreateDateTime(r.getCreateDateTime());
				}
            	
                session.delete(h);
            }            
            
			session.save(r);
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();
			return false;
		} finally {
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void delete(String hql) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();

            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);            	
            	h.setIsCancel(1);
            	h.setIsConfirm(0);
            	h.setBillStatus(0);
            	h.setIttl_status("-1");
		    	Iterator it = h.getBcStkRequestSubs().iterator();
		    	
		        while(it.hasNext()) {
		        	BCStkRequestSubBean sub = (BCStkRequestSubBean)it.next();
		        	sub.setIsCancel(1);
		        	sub.setIttl_status("-1");
		        }
		        
                session.update(h);
            }            
            			
			session.getTransaction().commit();
						
        } catch (HibernateException he) {
            he.printStackTrace();        
		} finally {
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public boolean restore(String hql) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();

            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);            	
            	h.setIsCancel(0);
            	h.setIsConfirm(1);
            	h.setBillStatus(1);
            	h.setIttl_status("0");
		    	Iterator it = h.getBcStkRequestSubs().iterator();
		    	
		        while(it.hasNext()) {
		        	BCStkRequestSubBean sub = (BCStkRequestSubBean)it.next();
		        	sub.setIsCancel(0);
		        	sub.setIttl_status("0");
		        }
		        
                session.update(h);
            }            
            			
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();        
			return false;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public boolean updateStatus(String poRefNo, String status) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			String hql ="FROM BCStkRequestBean WHERE docNo ='"+poRefNo+"'";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);            	
            	h.setIttl_status(status);
		    	
            	Iterator it = h.getBcStkRequestSubs().iterator();
            	while (it.hasNext()) {
					BCStkRequestSubBean sub = (BCStkRequestSubBean) it.next();
					sub.setIttl_status(status);
				}
            	
                session.update(h);
            }            
            			
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();        
			return false;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public boolean updateStatus(String stkReqDocNo, String[] rowOrderLineItem, String status) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			String hql ="FROM BCStkRequestBean WHERE docNo ='"+stkReqDocNo+"'";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);            	
            	
		    	Iterator it = h.getBcStkRequestSubs().iterator();		    	
		        while(it.hasNext()) {
		        	BCStkRequestSubBean sub = (BCStkRequestSubBean)it.next();
		        	
		        	for (int j = 0; j < rowOrderLineItem.length; j++) {
						if(rowOrderLineItem[j]!=null && sub.getRowOrder()==Integer.valueOf(rowOrderLineItem[j])) {
							sub.setIttl_status(status);
						}
					}		        	
		        }		        
                session.update(h);
            }            
            			
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();        
			return false;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public boolean updateAfterCreatePO(BCStkRequestBean stkReq,
			String[] rowOrderLineItem, String status) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			String hql ="FROM BCStkRequestBean WHERE docNo ='"+stkReq.getDocNo()+"'";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);
            	
            	h.setDocDate(stkReq.getDocDate());
            	h.setDepartCode(stkReq.getDepartCode());
            	h.setMyDescription(stkReq.getMyDescription());
            	h.setProjectCode(stkReq.getProjectCode());
            	h.setApCode("000");
            	h.setIttl_deptRequest(stkReq.getIttl_deptRequest());
            	
    			h.setIsConfirm(1);
    			h.setIsCancel(0);
    			h.setBillStatus(1);
    			h.setIttl_status(status);//ออกใบ PO แล้วจะเป็น 1
            	
		    	Iterator it = h.getBcStkRequestSubs().iterator();		    	
		        while(it.hasNext()) {
		        	BCStkRequestSubBean sub = (BCStkRequestSubBean)it.next();		        		        	
		        	
		        	sub.setDocDate(h.getDocDate());
		        	sub.setDepartCode(h.getDepartCode());
		        	sub.setProjectCode(h.getProjectCode());		        			        			     		        	
		        		        	
		        	Iterator it2 = stkReq.getBcStkRequestSubs().iterator();
//		        	System.out.println("################### : Line number");
		        	while (it2.hasNext()) {
						BCStkRequestSubBean stkReqSub = (BCStkRequestSubBean) it2.next();
//						System.out.println("line new="+stkReqSub.getLineNumber());
//						System.out.println("line query="+sub.getLineNumber());
						if(stkReqSub.getLineNumber().intValue()==sub.getLineNumber().intValue()) {
							
							sub.setItemCode(stkReqSub.getItemCode());
							sub.setDocDate(h.getDocDate());
							sub.setDepartCode(h.getDepartCode());
							
							sub.setQty(stkReqSub.getQty());
							sub.setRemainQty(stkReqSub.getRemainQty());
							sub.setProjectCode(h.getProjectCode());

							sub.setItemName(stkReqSub.getItemName());							
							sub.setIttl_unitName(stkReqSub.getIttl_unitName());
							sub.setIttl_division(stkReqSub.getIttl_division());
							
//							BCItemUnitBean unitBean = new BCItemUnitBean();
//							unitBean.setCode(stkReqSub.getBcitemUnit().getCode());							
//							sub.setBcitemUnit(unitBean);
							sub.setUnitCode(stkReqSub.getUnitCode());
							sub.setIsCancel(0);
							sub.setMyDescription(stkReqSub.getMyDescription());
							sub.setIttl_status(status);													
							
						}
					}		        			        	
		        }		        
                session.update(h);
            }            
            	
            
//			hql ="FROM BCStkRequestSubShowBean WHERE docNo ='"+stkReq.getDocNo()+"'";
//            org.hibernate.Query q = session.createQuery(hql);
//            List resultList = q.list();			
//
//            for(int i=0; i<resultList.size(); i++ ) {
//            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);
//            
//            }
            	
            	
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();        
			return false;
		} finally {
			session.close();
		}
	}	
	
	@SuppressWarnings("unchecked")
	public boolean updateStatusOfDeletePO(String stkReqDocNo, String[] rowOrderLineItem, String status) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			String rowOrder="";
			if(rowOrderLineItem!=null && rowOrderLineItem.length>0) {
				for (int i = 0; i < rowOrderLineItem.length; i++) {
					rowOrder = rowOrder + rowOrderLineItem[i] + ",";
				}
				if(rowOrder.length()>0){
					rowOrder = rowOrder.substring(0, rowOrder.length()-1);
				}else {
					rowOrder="0";
				}
			}
			
/*			for (int i = 0; i < rowOrderLineItem.length; i++) {
				if(rowOrderLineItem[i]!=null) {
					
					String hql = "FROM BCPurchaseOrderSubShowBean WHERE ittl_rowOrderOfStkReq="+rowOrderLineItem[i];
					Query poQ = session.createQuery(hql);
					List poList = poQ.list();
					System.out.println(hql);
					System.out.println("size="+poList.size());
					// ถ้า เจอ ittl_rowOrderOfStkReq = 1 ตัวใน BCPurchaseOrderSub แสดงว่ามีแค่ตัวเดียว update itemนั้น ใน bcstkRequestSub ให้ ittl_status=0ได้
					// ถ้าเจอ ittl_rowOrderOfStkReq >1 ตัว แสดงว่ามี PO ใบอื่นที่อ้าง item นี้อยู่ จะไม่ต้อง update: ittl_status
					if(poList!=null && poList.size()==1) {
						
						hql = "FROM BCStkRequestSubShowBean WHERE rowOrder = "+rowOrderLineItem[i];
						Query prQ = session.createQuery(hql);
						
						List prList = prQ.list();
						System.out.println(hql);
						System.out.println("size="+prList.size());
						
						if(prList!=null && prList.size()>0) {
							BCStkRequestSubShowBean stkReq = (BCStkRequestSubShowBean)prList.get(0);
							stkReq.setIttl_status("0");
							
							System.out.println("update BCStkRequestSub");
							session.update(stkReq);
								
							System.out.println("\n\n\n######## start: ที่ต้องมี ส่วนนี้ เพราะข้อมูลหลัง session.update(stkReq); ไม่ยอมแก้ให้ (ต้องทำ debug หาว่าเพราะอะไร) แล้วค่อยลบส่วนนี้ทิ้ง");
							hql = "FROM BCStkRequestSubShowBean WHERE rowOrder = "+rowOrderLineItem[i];
							Query aa = session.createQuery(hql);
							List bb = aa.list();
							if(bb!=null && bb.size()>0) {
								BCStkRequestSubShowBean cc = (BCStkRequestSubShowBean)bb.get(0);
								System.out.println(cc.getItemName() + ", status="+cc.getIttl_status());
							}
							System.out.println("######## end");
						}								
					}
				}
			}
			
			String hql = "FROM BCStkRequestBean WHERE docNo = '"+stkReqDocNo+"'";
			Query stkReqQ = session.createQuery(hql);
			
			List stkReqList = stkReqQ.list();
			System.out.println(hql);
			System.out.println("size="+stkReqList.size());
			
			if(stkReqList!=null && stkReqList.size()>0) {
				for(int i=0; i<stkReqList.size(); i++) {
					BCStkRequestBean stkReq = (BCStkRequestBean)stkReqList.get(i);
					
					boolean found_ittl_status_sub =false;
					Iterator it = stkReq.getBcStkRequestSubs().iterator();
					while (it.hasNext()) {
						BCStkRequestSubBean stkReqSub = (BCStkRequestSubBean) it.next();
						
						
						System.out.println(stkReqSub.getItemName() + ", status="+stkReqSub.getIttl_status());
						
						if(stkReqSub.getIttl_status().equals("1")) {													
							found_ittl_status_sub = true;
						}
					}
					
					if(found_ittl_status_sub == false) {
						stkReq.setIttl_status("0");
						
						session.update(stkReq);
						System.out.println("update BCStkRequest");
					}					
				}
			}*/
			
			String hql ="FROM BCStkRequestSubShowBean WHERE rowOrder in ("+rowOrder+")";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			
            
            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestSubShowBean h = (BCStkRequestSubShowBean)resultList.get(i);            	            	
		    	h.setIttl_status("0");		    	
                session.update(h);
            }            
            
			hql ="FROM BCStkRequestSubShowBean WHERE docNo = '"+stkReqDocNo+"' AND ittl_status='1'";
            q = session.createQuery(hql);
            resultList = q.list();			
            
            if(q.list().size()==0) {
    			hql ="FROM BCStkRequestBean WHERE docNo = '"+stkReqDocNo+"' AND ittl_status='1'";
                q = session.createQuery(hql);
                List resultList2 = q.list();  
                for (int i = 0; i < resultList2.size(); i++) {
                	BCStkRequestBean aa = (BCStkRequestBean)resultList2.get(i);
                	aa.setIttl_status("0");
                	session.update(aa);
				}
            }
            
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();        
			return false;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public boolean updateStatusOfEditPO(BCStkRequestBean stkReq, String[] rowOrderLineItem, String status, String poDocNo) {
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();

//############ start :new
/*			String rowOrder="";
			if(rowOrderLineItem!=null && rowOrderLineItem.length>0) {
				for (int i = 0; i < rowOrderLineItem.length; i++) {
					rowOrder = rowOrder + rowOrderLineItem[i] + ",";
				}
				if(rowOrder.length()>0){
					rowOrder = rowOrder.substring(0, rowOrder.length()-1);
				}else {
					rowOrder="0";
				}
			}
			String hql ="FROM BCStkRequestSubShowBean WHERE rowOrder in ("+rowOrder+")";
			System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+hql);
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			
            
            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestSubShowBean h = (BCStkRequestSubShowBean)resultList.get(i);            	            	
		    	h.setIttl_status(status);		    	
                session.update(h);
            }*/
//######### end :new
             
            
			
			String hql ="FROM BCStkRequestBean WHERE docNo ='"+stkReq.getDocNo()+"'";
            org.hibernate.Query q = session.createQuery(hql);
            List resultList = q.list();			

            for(int i=0; i<resultList.size(); i++ ) {
            	BCStkRequestBean h = (BCStkRequestBean)resultList.get(i);
            	
            	h.setDocDate(stkReq.getDocDate());
            	h.setDepartCode(stkReq.getDepartCode());
            	h.setMyDescription(stkReq.getMyDescription());
            	h.setProjectCode(stkReq.getProjectCode());
            	h.setApCode("000");
            	h.setIttl_deptRequest(stkReq.getIttl_deptRequest());
            	
    			h.setIsConfirm(1);
    			h.setIsCancel(0);
    			h.setBillStatus(1);
    			h.setIttl_status(status);//ออกใบ PO แล้วจะเป็น 1
            	
		    	Iterator it = h.getBcStkRequestSubs().iterator();		    	
		    	@SuppressWarnings("unused")
				int ii=0;
		        while(it.hasNext()) {
		        	BCStkRequestSubBean sub = (BCStkRequestSubBean)it.next();		        		        	
		        	
		        	sub.setDocDate(h.getDocDate());
		        	sub.setDepartCode(h.getDepartCode());		        	
		        	sub.setProjectCode(h.getProjectCode());	
		        			        	
		        	//private String	ittl_itemCode_ttl2;		        	
		        	//System.out.println("item ในใบ พ.1= "+sub.getItemCode());
		        	
		        	//จำนวน itemCode ใน stkReq <= ใน sub ที่ดึงมาจาก DB
		        	@SuppressWarnings("unused")
					boolean lineItemEdit[] = new boolean[4];
		        	@SuppressWarnings("unused")
					String item[] = new String[4];		        	
		        	Iterator it2 = stkReq.getBcStkRequestSubs().iterator();
		        	//System.out.println("####################################### sub เก่า รอบที่ i="+(++ii));
		        	while (it2.hasNext()) {
						BCStkRequestSubBean stkReqSub = (BCStkRequestSubBean) it2.next();
						//System.out.println(stkReqSub.getLineNumber()+"       "+sub.getLineNumber()+" boolean=" +(stkReqSub.getLineNumber()==sub.getLineNumber()));
						if(stkReqSub.getRowOrder().intValue()==sub.getRowOrder().intValue()) {
//						if(stkReqSub.getLineNumber().intValue()==sub.getRowOrder().intValue()) {
//							lineItemEdit[sub.getLineNumber()]=true;
//							item[sub.getLineNumber()] = stkReqSub.getItemCode();							
							sub.setItemCode(stkReqSub.getItemCode());
														
							sub.setQty(stkReqSub.getQty());
							sub.setRemainQty(stkReqSub.getRemainQty());
							
							sub.setItemName(stkReqSub.getItemName());
							
							sub.setIttl_unitName(stkReqSub.getIttl_unitName());
							sub.setIttl_division(stkReqSub.getIttl_division());
							
							sub.setUnitCode(stkReqSub.getUnitCode());
							sub.setMyDescription(stkReqSub.getMyDescription());
							
							sub.setIsCancel(0);
							sub.setIttl_status(status);		
							//System.out.println(sub.getItemName()+":"+sub.getQty()+"    "+sub.getIttl_status());
						}
					}		        	
		        	//ถ้าตัวไหนที่โดนลบออกไปในตอน edit po ให้คืนค่า item ตัวนั้นเป็น : ittl_status=0
//		        	for (int j = 0; j < lineItemEdit.length; j++) {
//		        		if (lineItemEdit[j]==false) {
//							sub.setIttl_status("0");							
//						}						
//					}
		        	
		        }		        
                session.update(h);
            }                                  
            	
			session.getTransaction().commit();
			return true;
        } catch (HibernateException he) {
            he.printStackTrace();        
			return false;
		} finally {
			session.close();
		}
		
	}

	@SuppressWarnings("unchecked")
	public boolean updateStatusAfterCreateInvoice(ActionForm form, String status) {
		
		BCAPInvoice2Form invForm = (BCAPInvoice2Form)form;
		
		if(invForm.getIttl_rowOrderOfStkReq()!=null && invForm.getIttl_rowOrderOfStkReq().length>0) {
		
			String rowOrder = "";
			for (int i = 0; i < invForm.getIttl_rowOrderOfStkReq().length; i++) {
				
				if(invForm.getIttl_rowOrderOfStkReq()[i]!=null) {
					rowOrder = rowOrder +""+ invForm.getIttl_rowOrderOfStkReq()[i] + ",";
				}											
			}	
			
			if(rowOrder.length()>0) {
				rowOrder = rowOrder.substring(0, rowOrder.length()-1);
			}else {
				rowOrder = "0";
			}
			
			String hql = "FROM BCStkRequestSubShowBean s  " +
	 		"WHERE  s.rowOrder in ( "+rowOrder+" )  ";
			Session session = null;

			try {
				sessionFactory = HibernateUtil.getSessionFactory();
				session = sessionFactory.openSession();
				session.beginTransaction();
								
	            org.hibernate.Query q = session.createQuery(hql);
	            List resultList = q.list();			

	            for(int i=0; i<resultList.size(); i++ ) {
	            	BCStkRequestSubShowBean h = (BCStkRequestSubShowBean)resultList.get(i);
	            	
	    			for (int x = 0; x < invForm.getIttl_rowOrderOfStkReq().length; x++) {	    				
	    				if(invForm.getIttl_rowOrderOfStkReq()[x]!=null && invForm.getIttl_rowOrderOfStkReq()[x].equalsIgnoreCase(""+h.getRowOrder())) {
	    					h.setPrice(Float.valueOf(invForm.getPrice()[x]));
	    					h.setAmount(h.getPrice()*h.getQty());
	    				}											
	    			}
	            	
	            	
	            	h.setIttl_status(status);            	    			        
	            	
	            	
	            		            	
	                session.update(h);
	            }                                    
	            	
				session.getTransaction().commit();
 				return true;
	        } catch (HibernateException he) {
	            he.printStackTrace();        
				return false;
			} finally {
				session.close();
			}
		}else {
			return false;
		}
	}


}
